package com.lawyer.service;

import io.swagger.annotations.ApiOperation;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import javax.persistence.EntityManager;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.lawyer.entity.RegimentalMember;
import com.lawyer.entity.RiderOrder;
import com.lawyer.entity.User;
import com.lawyer.model.BindingReq;
import com.lawyer.model.Message;
import com.lawyer.model.MessageConstant;
import com.lawyer.repository.RegimentalMemberRepository;
import com.lawyer.repository.RiderOrderRepository;
import com.lawyer.repository.UserRepository;

@Service
public class RegimentalMemberService {

	@Autowired
	private RegimentalMemberRepository regimentalMemberRepository;
	@Autowired
	private UserRepository userRepository;
	@Autowired
	private EntityManager entityManager;
	@Autowired
	private RiderOrderRepository riderOrderRepository;

	/**
	 * 骑手加入团
	 * 
	 * @param leaderId
	 * @param memberId
	 * @return
	 */
	public ResponseEntity<?> generalJoin(String leaderId, String memberId) {
		Message msg = new Message();
		try {

			String ids = leaderId + memberId;
			String id = UUID.nameUUIDFromBytes(ids.getBytes()).toString();

			RegimentalMember memberExists = regimentalMemberRepository.findOne(id);

			if (memberExists != null) {
				msg.setCode(MessageConstant.FAILED_CODE);
				msg.setMessage("已加入【" + memberExists.getLeaderName() + "】 的团,请勿重复加入");
				return new ResponseEntity<>(msg, HttpStatus.OK);
			}

			User leader = userRepository.findOne(leaderId);
			User member = userRepository.findOne(memberId);

			if (leader == null || member == null) {
				msg.setCode(MessageConstant.FAILED_CODE);
				msg.setMessage("没有找到团长或团员");
				return new ResponseEntity<>(msg, HttpStatus.OK);
			}
			RegimentalMember leaderMember = regimentalMemberRepository.findOne(leaderId);
			if (leaderMember == null) {
				msg.setCode(MessageConstant.FAILED_CODE);
				msg.setMessage("没有找该团");
				return new ResponseEntity<>(msg, HttpStatus.OK);
			}

			RegimentalMember regimentalMember = new RegimentalMember();

			regimentalMember.setId(id);

			regimentalMember.setLeaderId(leaderId);
			regimentalMember.setLeaderHeaderIco(leader.getHeaderIco());
			regimentalMember.setLeaderName(leader.getNickName());
			regimentalMember.setLeaderPhone(leader.getPhone());

			regimentalMember.setMemberId(memberId);
			regimentalMember.setMemberHeaderIco(member.getHeaderIco());
			regimentalMember.setMemberName(member.getNickName());
			regimentalMember.setMemberPhone(member.getPhone());

			if (leaderMember.getTopId().equals(leaderId)) {
				regimentalMember.setTopId(leaderMember.getTopId() + "_");
			} else {
				regimentalMember.setTopId(leaderMember.getTopId() + "_" + leaderId + "_");
			}

			regimentalMemberRepository.save(regimentalMember);

			updateOrderLeader(memberId, leaderId);
		} catch (Exception e) {
			msg.setCode(MessageConstant.FAILED_CODE);
			msg.setMessage(MessageConstant.FAILED_MSG);
		}
		return new ResponseEntity<>(msg, HttpStatus.OK);
	}

	/**
	 * 站长加入团
	 * 
	 * @param leaderId
	 * @param memberId
	 * @return
	 */
	public ResponseEntity<?> regimentJoin(String leaderId, String memberId) {
		Message msg = new Message();
		try {

			RegimentalMember leaderMember = regimentalMemberRepository.findOne(leaderId);
			if (leaderMember == null) {
				msg.setCode(MessageConstant.FAILED_CODE);
				msg.setMessage("没有找到该团");
				return new ResponseEntity<>(msg, HttpStatus.OK);
			}

			RegimentalMember zhanZhangMember = regimentalMemberRepository.findOne(memberId);

			if (zhanZhangMember == null) {
				msg.setCode(MessageConstant.FAILED_CODE);
				msg.setMessage("没有找到站长【" + memberId + "】");
				return new ResponseEntity<>(msg, HttpStatus.OK);
			}

			if (zhanZhangMember.getTopId().contains(leaderId)) {
				msg.setCode(MessageConstant.FAILED_CODE);
				msg.setMessage("已加入【" + leaderMember.getLeaderName() + "】 的团,请勿重复加入");
				return new ResponseEntity<>(msg, HttpStatus.OK);
			}

			if (zhanZhangMember.getStarLevel() == leaderMember.getStarLevel()) {
				msg.setCode(MessageConstant.FAILED_CODE);
				msg.setMessage("站长不能加入站长");
				return new ResponseEntity<>(msg, HttpStatus.OK);
			}

			zhanZhangMember.setTopId(leaderMember.getTopId() + "_");
			regimentalMemberRepository.save(zhanZhangMember);

			// 更新站长下所有骑手topId
			CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();

			CriteriaQuery<RegimentalMember> criteriaQuery = criteriaBuilder.createQuery(RegimentalMember.class);

			Root<RegimentalMember> root = criteriaQuery.from(RegimentalMember.class);

			criteriaQuery.orderBy(criteriaBuilder.desc(root.get("createdDate")));

			// 查询条件
			List<Predicate> predicates = new ArrayList<>();

			predicates.add(criteriaBuilder.equal(root.get("leaderId"), memberId));

			predicates.add(criteriaBuilder.notEqual(root.get("id"), memberId));

			predicates.add(criteriaBuilder.like(root.get("topId"), "%" + memberId + "%"));

			// 将所有条件用 and 联合起来
			if (!CollectionUtils.isEmpty(predicates)) {
				criteriaQuery.where(criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()])));
			}

			TypedQuery<RegimentalMember> createQuery = entityManager.createQuery(criteriaQuery);
			List<RegimentalMember> childs = createQuery.getResultList();

			for (RegimentalMember regMember : childs) {
				regMember.setTopId(zhanZhangMember.getTopId() + regMember.getTopId());
				regimentalMemberRepository.save(regMember);
			}

		} catch (Exception e) {
			msg.setCode(MessageConstant.FAILED_CODE);
			msg.setMessage(MessageConstant.FAILED_MSG);
		}
		return new ResponseEntity<>(msg, HttpStatus.OK);
	}

	/**
	 * 用户绑定代理
	 */

	public void binding(String userId, String agentId) {
		try {

			User agent = userRepository.findOne(agentId);

			User user = userRepository.findOne(userId);

			if (user == null || agent == null) {
				return;
			}

			if (StringUtils.isNotEmpty(user.getAgentId())) {
				return;

			}

			if ("0".equals(agent.getUserType())) {
				return;
			}

			if ("1".equals(user.getUserType())) {
				return;
			}
			user.setAgentId(agent.getId());
			user.setAgentCode(agentId);
			user.setBindingDate(new Date());
			userRepository.save(user);

		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	public List<RegimentalMember> findMyTeam(String userId) {
		Message msg = new Message();
		List<RegimentalMember> result = new ArrayList<RegimentalMember>();

		if (StringUtils.isEmpty(userId)) {
			msg.setCode(MessageConstant.FAILED_CODE);
			msg.setMessage("userId为空或用户不存在");
			return result;
		}

		RegimentalMember leaderMember = regimentalMemberRepository.findOne(userId);
		if (leaderMember == null) {
			msg.setCode(MessageConstant.FAILED_CODE);
			msg.setMessage("没有找该团");
			return result;
		}
		CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();

		CriteriaQuery<RegimentalMember> criteriaQuery = criteriaBuilder.createQuery(RegimentalMember.class);

		Root<RegimentalMember> root = criteriaQuery.from(RegimentalMember.class);

		criteriaQuery.orderBy(criteriaBuilder.desc(root.get("createdDate")));

		// 查询条件
		List<Predicate> predicates = new ArrayList<>();

		predicates.add(criteriaBuilder.notEqual(root.get("id"), userId));

		predicates.add(criteriaBuilder.like(root.get("topId"), "%" + userId + "%"));

		// 将所有条件用 and 联合起来
		if (!CollectionUtils.isEmpty(predicates)) {
			criteriaQuery.where(criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()])));
		}

		TypedQuery<RegimentalMember> createQuery = entityManager.createQuery(criteriaQuery);
		result = createQuery.getResultList();

		return result;
	}

	public List<RegimentalMember> orderTotalQuantity(String userId) {
		Message msg = new Message();
		List<RegimentalMember> result = new ArrayList<RegimentalMember>();

		if (StringUtils.isEmpty(userId)) {
			msg.setCode(MessageConstant.FAILED_CODE);
			msg.setMessage("userId为空或用户不存在");
			return result;
		}

		RegimentalMember leaderMember = regimentalMemberRepository.findOne(userId);
		if (leaderMember == null) {
			msg.setCode(MessageConstant.FAILED_CODE);
			msg.setMessage("没有找该团");
			return result;
		}
		CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();

		CriteriaQuery<RegimentalMember> criteriaQuery = criteriaBuilder.createQuery(RegimentalMember.class);

		Root<RegimentalMember> root = criteriaQuery.from(RegimentalMember.class);

		criteriaQuery.orderBy(criteriaBuilder.desc(root.get("createdDate")));

		// 查询条件
		List<Predicate> predicates = new ArrayList<>();

		predicates.add(criteriaBuilder.notEqual(root.get("id"), userId));

		predicates.add(criteriaBuilder.like(root.get("topId"), "%" + userId + "%"));

		// 将所有条件用 and 联合起来
		if (!CollectionUtils.isEmpty(predicates)) {
			criteriaQuery.where(criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()])));
		}

		TypedQuery<RegimentalMember> createQuery = entityManager.createQuery(criteriaQuery);
		result = createQuery.getResultList();

		return result;
	}

	public void updateOrderLeader(String userId, String leaderId) {

		CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();

		CriteriaQuery<RiderOrder> criteriaQuery = criteriaBuilder.createQuery(RiderOrder.class);

		Root<RiderOrder> root = criteriaQuery.from(RiderOrder.class);

		// 查询条件
		List<Predicate> predicates = new ArrayList<>();

		predicates.add(criteriaBuilder.equal(root.get("userId"), userId));

		// 将所有条件用 and 联合起来
		if (!CollectionUtils.isEmpty(predicates)) {
			criteriaQuery.where(criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()])));
		}

		TypedQuery<RiderOrder> createQuery = entityManager.createQuery(criteriaQuery);

		List<RiderOrder> result = createQuery.getResultList();

		User leader = userRepository.findOne(leaderId);

		for (RiderOrder riderOrder : result) {
			riderOrder.setLeaderId(leaderId);
			riderOrder.setLeaderHeaderIco(leader.getHeaderIco());
			riderOrder.setLeaderName(leader.getNickName());
			riderOrderRepository.save(riderOrder);
		}

	}

}